import requests,json,re,os,time
from os.path import abspath, dirname
from lxml import etree

class wzbz():
    def __init__(self):
            
        self.base_url = 'https://pvp.qq.com/web201605/js/herolist.json'
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"
        }
        self.IMAGEPATH = dirname(abspath(__file__))+'/images2'
        if os.path.exists(self.IMAGEPATH):
            os.rmdir(self.IMAGEPATH)
        os.mkdir(self.IMAGEPATH)

    def get_datas(self,url):
        response = requests.get(url, headers=self.headers)
        return response.content

    def parse_datas(self,datas):
        html = etree.HTML(datas)
        hero = html.xpath('//div[@class="crumb"]/label/text()')[0]
        skin_names = html.xpath('//div[@class="pic-pf"]/ul[@class="pic-pf-list pic-pf-list3"]/@data-imgname')[0]
        skin_names = re.sub('[\d]','',str(skin_names)).replace('&','').split('|')
        yield hero,skin_names

    def save_datas(self,hero,skin_names,ename):
        for skin_num in range(1, len(skin_names)+1):
            skin_url = 'http://game.gtimg.cn/images/yxzj/img201606/skin/hero-info/'+ename+'/'+ename+'-bigskin-'+str(skin_num)+'.jpg'
            skin_data = self.get_datas(skin_url)
            with open(f'{self.IMAGEPATH}/{hero}-{skin_names[skin_num - 1]}.jpg', 'wb') as f:
                print('正在下载图片：', hero + '-' + skin_names[skin_num - 1])
                f.write(skin_data)
    def main(self):
        for i in json.loads(self.get_datas(self.base_url)):
            ename = str(i['ename'])
            detail_url = 'https://pvp.qq.com/web201605/herodetail/' + str(ename) + '.shtml'        
            for j in self.parse_datas(self.get_datas(detail_url)):
                self.save_datas(j[0],j[1],ename)

if __name__ == "__main__":
    start = time.time()
    wzbz().main()
    end = time.time()
    print(f'{end-start:.3f}s')
